package bean;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Component;

import java.util.Properties;

@Component
public class ErrorCodeMapping implements InitializingBean {
    @Value("${app.config.errorCodeFile:}")
    private String customErrorCodeMapping;

    private String defaultErrorPropFile = "error.properties";
    public static Properties ERROR_MAPPING;

    public static String getErrorMsg(String errorCode){
        return ERROR_MAPPING.getProperty(errorCode);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        ClassPathResource resource = new ClassPathResource(defaultErrorPropFile);
        EncodedResource errorCodeSource = new EncodedResource(resource, "UTF-8");
        ERROR_MAPPING = PropertiesLoaderUtils.loadProperties(errorCodeSource);
        if(customErrorCodeMapping!=null && !"".equals(customErrorCodeMapping)){
            ResourceLoader loader = new DefaultResourceLoader();
            Resource customResource = loader.getResource(customErrorCodeMapping);
            EncodedResource customErrorCodeSource = new EncodedResource(customResource, "UTF-8");
            Properties properties = PropertiesLoaderUtils.loadProperties(customErrorCodeSource);
            ERROR_MAPPING.putAll(properties);
        }
    }
}
